# -*- coding: utf-8 -*-
from crm.models import Members,Salesperson,Agent,Furtherinterest,Projects,Follow_up
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import loader, Context

"""用户导出"""
def export (request):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    
    if request.method == 'GET':
        agent_list = Agent.objects.order_by('id')
        project_list = Projects.objects.order_by('id')
        return render_to_response('csv_ex.html',{'agent_list':agent_list,'project_list':project_list})

    else:
        page=int(request.POST.get('page','1'))
        p_id=request.POST.get('p_id','0')
        a_id=request.POST.get('a_id','0')
        sales=request.POST.get('sales','')
        name=request.POST.get('name','')
        interlevel=request.POST.get('interlevel','all')
        status=request.POST.get('status','all')
        start_date=request.POST.get('start_date','begin')
        end_date=request.POST.get('end_date','now')

        if start_date == 'begin' and end_date =='now':
            members=Members.objects.filter()
        elif start_date =='begin' and end_date != 'now':
            members=Members.objects.filter(regtime__lte=end_date)
        elif start_date != 'begin' and end_date =='now':
            members=Members.objects.filter(regtime__gte=start_date)
        else:
            members=Members.objects.filter(regtime__range=(start_date, end_date))

        if p_id !='0':
            members=members.filter(projects__pk=int(p_id))
        if a_id !='0':
            members=members.filter(agent__pk=int(a_id))
        if name:
            members=members.filter(name=name)
        if interlevel !='all':
            members=members.filter(interlevel=interlevel)
        if status != 'all':
            members=members.filter(status=status)
        if request.session['level']=='sales':
            members=members.filter(salesperson__id=request.session['id'])
        else:
            if sales:
                members=members.filter(salesperson__name=sales)
        members=members.order_by('-id')

        d = []
        for o in members:
            try:
                agent=o.agent.name
            except:
                agent='undefine'
            try:
                salesperson=o.salesperson.name
            except:
                salesperson='undefine'
            try:
                projects=o.projects.name
            except:
                projects='undefine'
            if o.received_emaill == 1 :
                received_emaill ='Y'
            else:
                received_emaill='N'
            if o.received_hardcopy == 1 :
                received_hardcopy ='Y'
            else:
                received_hardcopy='N'
            #follow up data
            statusinfo=fpinfo=''
            fp_list=Follow_up.objects.filter(members=o).order_by('-timeline')
            i=1
            for fp in fp_list:
                if fp.status==0 or fp.status=='0':
                    statusinfo+=str(i)+': '+"Not yet"
                if fp.status==1 or fp.status=='1':
                    statusinfo+=str(i)+': '+"Can't reach"
                if fp.status==2 or fp.status=='2':
                    statusinfo+=str(i)+': '+"App sch'd"
                if fp.status==3 or fp.status=='3':
                    statusinfo+=str(i)+': '+"Under cons"
                if fp.status==4 or fp.status=='4':
                    statusinfo+=str(i)+': '+"Call later"
                if fp.status==5 or fp.status=='5':
                    statusinfo+=str(i)+': '+"Conflict"
                if fp.status==6 or fp.status=='6':
                    statusinfo+=str(i)+': '+"No call"
                if fp.status==7 or fp.status=='7':
                    statusinfo+=str(i)+': '+"Enrolled"
                statusinfo=statusinfo+'('+str(fp.timeline)+')\n'
                fpinfo+=str(i)+': '+fp.remarks+"\n"
                i+=1
            try:
                if o.regtime=='none' or o.regtime=='None' or o.regtime==None:
                    o.regtime='0000-00-00 00:00:00'
                if o.last_contact=='none' or o.last_contact=='None' or o.last_contact==None:
                    o.last_contact='0000-00-00 00:00:00'
            except:
                pass
            #fpinfo='tttttt\ndddd'
            #d.append((o.id,o.name,o.get_status_display(),fpinfo,agent,projects,salesperson,o.get_interlevel_display(),o.job_title,o.company,o.work_experience,o.get_education_display(),received_emaill,received_hardcopy,o.tel_h,o.tel_o,o.tel_m,o.email,o.address,o.regtime))
            #d.append((o.id,o.name,statusinfo,fpinfo,agent,projects,salesperson,o.get_interlevel_display(),o.job_title,o.company,o.work_experience,o.get_education_display(),received_emaill,received_hardcopy,o.tel_h,o.tel_o,o.tel_m,o.email,o.address,o.regtime,o.last_contact))
            d.append((o.id,o.name,statusinfo,agent,projects,salesperson,o.get_interlevel_display(),o.job_title,o.company,o.work_experience,o.get_education_display(),received_emaill,received_hardcopy,o.tel_h,o.tel_o,o.tel_m,o.email,o.address,o.regtime,o.last_contact))

        response = HttpResponse(mimetype='text/csv')
        response['Content-Disposition'] = 'attachment; filename=%s' % 'members.csv'
        t = loader.get_template('csv.html')
        c = Context({
            'data': d,
        })
        a=t.render(c)
        #a = a.decode('UTF-8').encode('gb2312')
        #a = a.replace('encoding="UTF-8"', 'encoding="gb2312"')
        #a = a.replace('\\', '')
        response.write(t.render(c))
        return response

"""用户导入"""
def upload (request):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    
    if request.method == 'GET':
        return render_to_response('csv_im.html')

    else:
        file_obj = request.FILES.get('file', None)
        if file_obj:
            import csv
            import StringIO
            buf = StringIO.StringIO(file_obj.read())
            try:
                reader = csv.reader(buf)
            except:
                return render_to_response('csv_im.html',
                    {'message':'You need to upload a csv file!'})
            agent_list = Agent.objects.all()
            project_list = Projects.objects.all()
            sales_list = Salesperson.objects.all()
            for row in reader:
                if row[0] == 'ID' or row[1]=='name':
                    pass
                else:
                    if row[3] !='' or row[3] !='undefine':
                        a=agent_list.filter(name=row[3])
                        if a:
                            a_id=a[0].id
                        else:
                            a_id=0
                    else:
                        a_id=0
                    if row[4] !='' or row[4] !='undefine':
                        p=project_list.filter(name=row[4])
                        if p:
                            p_id = p[0].id
                        else:
                            p_id = 0
                    else:
                        p_id = 0
                    if row[4] !='' or row[4] !='undefine':
                        s=sales_list.filter(name=row[5])
                        if s:
                            s_id=s[0].id
                        else:
                            s_id=0
                    else:
                        s_id = 0
                    if 'reach' in row[2].lower():
                        status_id = '1'
                    elif 'app' in row[2].lower():
                        status_id = '2'
                    elif 'under' in row[2].lower():
                        status_id = '3'
                    elif 'later' in row[2].lower():
                        status_id = '4'
                    elif row[2].lower() == 'conflict':
                        status_id = '5'
                    elif 'no call' in row[2].lower():
                        status_id = '6'
                    elif row[2].lower() == 'enrolled':
                        status_id = '7'
                    else:
                        status_id = '0'
                    if row[6].lower() =='hi':
                        i_id = '1'
                    elif row[6].lower() == 'si':
                        i_id = '2'
                    elif row[6].lower() == 'ni':
                        i_id = '3'
                    elif row[6].lower() == 'nt':
                        i_id = '4'
                    else:
                        i_id = '0'
                    if row[10].lower() == 'secondary school':
                        e_id = '1'
                    elif row[10].lower() == 'diplma':
                        e_id = '2'
                    elif 'bachelor' in row[10].lower():
                        e_id = '3'
                    elif 'master' in row[10].lower():
                        e_id = '4'
                    elif row[10].lower() =='ph.d.':
                        e_id = '5'
                    else:
                        e_id = '0'
                    if 'y' in row[11].lower():
                        r_e = 1
                    else:
                        r_e = 0
                    if 'y' in row[12].lower():
                        r_h = 1
                    else:
                        r_h = 0
                    rtime=row[18]
                    ltime=row[19]
                    if row[18]=='none' or row[18]=='None' or row[18]==None:
                        rtime='0000-00-00 00:00:00'
                    if row[19]=='none' or row[19]=='None' or row[19]==None:
                        ltime='0000-00-00 00:00:00'
                    obj = Members(
                    name=row[1],
                    status=status_id,
                    agent_id=a_id,
                    projects_id=p_id,
                    salesperson_id=s_id,
                    interlevel=i_id,
                    job_title=row[7],
                    company=row[8],
                    work_experience=row[9],
                    education=e_id,
                    received_emaill=r_e,
                    received_hardcopy=r_h,
                    tel_h=row[13],
                    tel_o=row[14],
                    tel_m=row[15],
                    email=row[16],
                    address=row[17],
                    regtime=rtime,
                    last_contact=ltime,
                    message='',
                    )
                    obj.save()
            return render_to_response('csv_im.html',{'message':'succeed!'})
        else:
            return render_to_response('csv_im.html',
                {'message':'please upload a csv file'})